<template>
  <van-nav-bar
    title="商品详情"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-image width="100%" height="200" :src="productData.img" />
  <van-cell
    :title="productData.name"
    :value="'¥ ' + productData.price"
    value-class="price"
    style="color: black"
  />
  <div class="subTitle">
    {{ productData.subTitle }}
  </div>
  <van-cell title="商品详情,仅供参考" icon="description" />

  <div class="description">
    <div v-html="productData.description"></div>
  </div>

  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" @click="onClickIcon" />
    <van-action-bar-icon icon="cart-o" text="购物车" @click="onClickIcon" />
    <van-action-bar-icon icon="shop-o" text="店铺" @click="onClickIcon" />
    <van-action-bar-button
      type="danger"
      text="加入购物车"
      @click="onClickButton"
    />
  </van-action-bar>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { productApi,cartApi } from "@/api/index";
import { showToast,showSuccessToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import {appStore}  from '@/store/appStore'
import {storeToRefs}  from "pinia"

//把存储对象转成引用对象
let { userId,phone} =   storeToRefs(appStore())
const route = useRoute();
const router = useRouter();

//商品的信息
const productData = reactive({
  id: "",
  name: "",
  subTitle: "",
  description: "",
  price: 0,
  img: "",
});

//钩子函数
onMounted(() => {
  //获取路由url上的商品id
  if (route.query.id != undefined) {
    productData.id = route.query.id.toString();
  }
  callProductApi();
});
//查询商品信息api
const callProductApi = () => {
  productApi.selectById.call({ id: productData.id }).then((res: any) => {
    productData.id = res.id;
    productData.name = res.name;
    productData.subTitle = res.subTitle;
    productData.description = res.description;
    productData.price = res.price;
    productData.img = res.img;
  });
};

//点击跳转购物车页面
const onClickIcon = () => {
  router.push({ name: "cart" });
};

//加入购物车
const onClickButton = () => {
  if(userId.value===0){
    router.push({name:"user-login"})
    showSuccessToast("请先登录")
    return
  }
  const params={
    productId:productData.id,
    productName:productData.name,
    productSubtitle:productData.subTitle,
    productImg:productData.img,
    productPrice:productData.price,
    productQty:1,
    userId:userId.value//先给个固定的用户
  }
  cartApi.add.call(params).then((res:any)=>{
    showSuccessToast("添加购物车成功")
  })
};
const onClickLeft = () => history.back();
</script>


<style>
.subTitle {
  color: #e4393c;
  font-size: 12px;
  padding: 0px 10px;
}

.description {
  color: #ccc;
  font-size: 12px;
  padding: 0px 10px;
  line-height: 25px;
}

.description img {
  width: 100%;
  height: 100%;
}
.van-action-bar {
  z-index: 2;
}
</style>